package com.example.demo.util;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by song on 2018/1/25.
 */
public class LangUtil {
    public static int getSafeInt(Object obj){
        if(obj == null)
            return 0;
        if(obj instanceof BigInteger){
            return ((BigInteger) obj).intValue();
        }
        if(obj instanceof BigDecimal){
            return ((BigDecimal) obj).intValue();
        }
        if(obj instanceof Integer){
            return (Integer)obj;
        }
        if(obj instanceof Double){
            return ((Double) obj).intValue();
        }
        return 0;
    }

    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static void copyPropertiesIgnoreNull(Object src, Object target){
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }

    public static void copyPropertiesIgnoreNull(Object src, Object target, String[] ignores){
        BeanUtils.copyProperties(src, target, (String[]) ArrayUtils.addAll(getNullPropertyNames(src), ignores));
    }
}
